package com.mastercard

import java.text.SimpleDateFormat
import java.util.HashMap;
import grails.converters.JSON
import org.apache.shiro.SecurityUtils
import org.apache.commons.lang.time.DateUtils
import com.mastercard.auth.User
import com.mastercard.common.constants.CommonConstants
import com.mastercard.util.*

import org.codehaus.groovy.grails.commons.DefaultGrailsApplication
import org.codehaus.groovy.grails.web.converters.ConverterUtil

class ExpenseController {
    static scaffold = true
	def profileService
	
	def index() {
		
	}
	
	def viewSummary() {
		User loginUsr = SecurityUtils.subject.session.getAttribute(CommonConstants.LOGIN_USER)
		User usr = profileService.getProfileById(loginUsr.id);
		List cards = usr.creditCards
		double todaySpend = 0
		double sevenDaysSpend = 0
		double monthSpend = 0
		double yearSpend = 0
		Date dt = new Date()
		SimpleDateFormat monthsdf = new SimpleDateFormat("MM")
		SimpleDateFormat yeardf = new SimpleDateFormat("yyyy")
		long currentTime = dt.getTime()
		final long MILLIS_IN_DAY = 1000*60*60*24
		for(int i=0; i<cards.size(); i++){
			CreditCard card = cards.get(i)
			List txnList = card.transactions
			for (int j=0 ; j < txnList.size(); j++) {
				Transaction txn = txnList.get(j);
				if (DateUtils.isSameDay(txn.datetime, dt)) {
					todaySpend+= txn.amount
				}
				if (monthsdf.format(txn.datetime).equals(monthsdf.format(dt))) {
					monthSpend += txn.amount
				}
				if (yeardf.format(txn.datetime).equals(yeardf.format(dt))) {
					yearSpend += txn.amount
				}
				long compareTime = txn.datetime.getTime()
				long noOfDays = 0;
				for( ; compareTime < currentTime; noOfDays++ ) {
					compareTime+=MILLIS_IN_DAY
				}
				if (noOfDays <= 7) {
					sevenDaysSpend += txn.amount
				}
			}
		}
		HashMap map = new HashMap()
		map.put("todayspend", todaySpend)
		map.put("monthspend", monthSpend)
		map.put("yearspend", yearSpend)
		map.put("sevendayspend", sevenDaysSpend)
		
		def json = new JSON(map)
		render (text:json, contentType:"application/json")
		
	}
	
	def viewSpendingChart() {
		User loginUsr = SecurityUtils.subject.session.getAttribute(CommonConstants.LOGIN_USER)
		User usr = profileService.getProfileById(loginUsr.id);
		List cards = usr.creditCards
		SimpleDateFormat monthsdf = new SimpleDateFormat("MM")
		double janSpend = 0
		double febSpend = 0
		double marSpend = 0
		double aprSpend = 0
		double maySpend = 0
		double junSpend = 0
		double julSpend = 0
		double augSpend = 0
		double sepSpend = 0
		double octSpend = 0
		double novSpend = 0
		double decSpend = 0
		HashMap map = new HashMap()
		for(int i=0; i<cards.size(); i++){
			CreditCard card = cards.get(i)
			janSpend = 0
			febSpend = 0
			marSpend = 0
			aprSpend = 0
			maySpend = 0
			junSpend = 0
			julSpend = 0
			augSpend = 0
			sepSpend = 0
			octSpend = 0
			novSpend = 0
			decSpend = 0
			def results = Transaction.findAll("from Transaction as t where credit_card_id =:cardid and datetime > sysdate - 365", [cardid: card.number])
			for (int j=0; j<results.size(); j++) {
				Transaction txn = results.get(j)
				if (monthsdf.format(txn.datetime).equals("01")) {
					janSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("02")) {
					febSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("03")) {
					marSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("04")) {
					aprSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("05")) {
					maySpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("06")) {
					junSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("07")) {
					julSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("08")) {
					augSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("09")) {
					sepSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("10")) {
					octSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("11")) {
					novSpend += txn.amount
				} else if (monthsdf.format(txn.datetime).equals("12")) {
					decSpend += txn.amount
				}
			}
			List spending = new ArrayList()
			spending.add(janSpend)
			spending.add(febSpend)
			spending.add(marSpend)
			spending.add(aprSpend)
			spending.add(maySpend)
			spending.add(junSpend)
			spending.add(julSpend)
			spending.add(augSpend)
			spending.add(sepSpend)
			spending.add(octSpend)
			spending.add(novSpend)
			spending.add(decSpend)
			map.put(card.bank.name, spending)
		}
		def json = new JSON(map)
		render (text:json, contentType:"application/json")
	}
	
	def viewTransaction() {
		User loginUsr = SecurityUtils.subject.session.getAttribute(CommonConstants.LOGIN_USER)
		ConverterUtil.getInstance().grailsApplication = new DefaultGrailsApplication()
		def cardNo = params.get('cardno')
		def transactionID = params.get('transactionid')
		
		//should do validation here
		
		
		def transaction = Transaction.findById(transactionID);
		
		//Unable to test. If successful, the converter util will auto populate into hasmap and render
		//def json = new JSON(transaction).toString()
		HashMap map = new HashMap()
		map.put("date", transaction.getDateTime())
		map.put("amount", transaction.getAmount())
		map.put("type", transaction.getType())
		map.put("currency", transaction.getCurrency())
		
		def json = new JSON(map)
		render (text:json, contentType:"application/json")
	}
	
	def search() {
		ConverterUtil.getInstance().grailsApplication = new DefaultGrailsApplication()
		def cardNo = params.get('cardno')
		def cal = Calendar.getInstance()
		cal.add(Calendar.MONTH, -1)
		def date = cal.getTime()
		def transaction = Transaction.findByBelongsToAndCreatedDate(cardNo, date)
		
		def json = new JSON(transaction).toString()
		
		render (text:json, contentType:"application/json")
	}
}
